/**
 * Created by admin on 2017/6/13.
 */
import {Cache, cache_keys,env} from './util';

export const quickLogin = async function(callback) {
  var data = {
    grant_type: 'sms_token',
    access_token: this.sms_token,
    mobile: this.mobile,
    code: this.code,
    type: 'direct'
  };

  var url = EventBus.$Config.baseUrl + 'api/oauth/sms';

  await login.call(this, data, url, 1, callback);
};

export const openidLogin = async function (callback) {
  var data = {};

  var url = EventBus.$Config.baseUrl + 'api/oauth/quicklogin';
  await login.call(this, data, url, 3, callback);
};
export const login = async function(data, url, type, callback) {
  var callType = typeof callback;

  try {
    var res = await (() => {
      if (env.isWechat) {
        data.open_type = 'wechat';
        var openid = this.$route.query.openid || this.$route.query['?openid'];
        if (openid) {
          data.open_id = openid;
        }
      }

      var utm = Cache.get(cache_keys.utm);
      if (utm) data = Object.assign(data, utm);

      return EventBus.$http.post(url, data);
    })();

    var result = res.data;

    if (result.access_token) {
      result.access_token = result.token_type + ' ' + result.access_token;
      result.expires_in = result.expires_in || 315360000;  // token不过期
      result.expires = Date.now() + (result.expires_in - 300) * 1000;

      Cache.set(cache_keys.token, result, 0, null);

      setUserCache.call(this);

      // 联合登录的cookie
      if (result.vipeak_user && result.vipeak_sso) {
        Cache.cookieStorage.setItem('vipeak_user', result.vipeak_user, {expire: Date.now() + 31536000000});
        Cache.cookieStorage.setItem('vipeak_sso', result.vipeak_sso, {expire: Date.now() + 31536000000});
      }

      // 绑定野练的openid
      var activity = Cache.get(cache_keys.activity_openid);
      if (activity && activity.open_id && !activity.binded) {
        bindActivityOpenid.call(this, activity.open_id);
      }

      // this.$refs.button && this.$refs.button.done();

      if (callback) {
        if (callType === 'function') {
          callback.call(this, result);
          return null;
        } else if (callType === 'object') {
          if (callback.onSuccess && typeof callback.onSuccess === 'function') {
            callback.onSuccess.call(this, result);
            return null;
          }
        }
      }

      var from = this.$route.query.from;
      var source = this.$route.query.source;
      if (from) {
        window.location.href = from;
      } else if (source) {
        this.$router.replace(source);
      } else {
        this.$router.replace({name: 'city_list'});
      }
    } else {
      // this.$refs.button && this.$refs.button.done();

      if (callback) {
        if (callType === 'function') {
          callback.call(this, result);
          return null;
        } else if (callType === 'object') {
          if (callback.onError && typeof callback.onError === 'function') {
            callback.onError.call(this, result);
            return null;
          }
        }
      }

      if (type === 0) {
        EventBus.$Modal.info({title:'消息提示',body:'用户名或密码输入错误'});
      } else if (type === 1) {
        EventBus.$Modal.info({title:'消息提示',body:'验证码错误'});
        // this.$Alert('验证码错误');
      }
    }
  } catch (e) {
    console.error(e);
    // this.$refs.button && this.$refs.button.done();

    if (callback && typeof callback === 'function') {
      callback.call(this, {
        status: false
      });
      return null;
    }

    if (type === 0) {
      EventBus.$Modal.info({title:"消息提示",body:'用户名或密码输入错误'});
    } else if (type === 1) {
      EventBus.$Modal.info({title:"消息提示",body:'验证码错误'});
    }
  }
};

export const logout = function (name) {
  Cache.remove(cache_keys.token);
  Cache.cookieStorage.removeItem('vipeak_user');
  Cache.cookieStorage.removeItem('vipeak_sso');
  this.$router.push({name: name || 'login-quick'});
};


export const getOpenid = function () {
  var from = this.$route.query.from;
  var source = this.$route.query.source;
  var pathname = window.location.pathname;

  // var query = { type: 'oauth' };
  // if (from) {
  //   query.from = from;
  // } else if (source) {
  //   query.source = source;
  // }
let url=this.$route.path;
  // let url = this.$router.stringifyPath({ name: this.$route.name, query });
  if ( this.$router.mode === 'hash' ) url = '#' + url;
  url += '?type=oauth';
  if (from) {
    url+='&from='+from;
  } else if(source){
    url+='&source='+source;
  }

  url = decodeURIComponent(url);

  url = EventBus.$Config.baseUrl + 'oauth/wxlogin?redirect_url=' + encodeURIComponent(window.location.origin + pathname + url + '&');
  window.location.href = url;
};

export const getActivityOpenid = function () {
  var activity = Cache.get(cache_keys.activity_openid);
  if (activity && activity.openid) {
    if (!activity.openid.binded) {
      var oauth = Cache.get(cache_keys.token);
      if (oauth && oauth.access_token) {
        bindActivityOpenid.call(this, activity.openid);
      }
    }

    return true;
  } else {
    var path=this.$route.fullpath
    var query = {
      type: 'activity',
      source: path
    };

    var origin = window.location.origin;
    var pathname = window.location.pathname;
    // let url = this.$router.stringifyPath({ name: 'user-quick-login', query });
    if ( this.$router.mode === 'hash' ) url = '#!' + url;
    url+="?type=activity&source="+query.source;
    url = decodeURIComponent(url);

    url = EventBus.$Config.baseUrl + 'activity/oauth/wxlogin?redirect_url=' + encodeURIComponent(origin + pathname + url + '&');

    window.location.href = url;

    return false;
  }
};

export const bindActivityOpenid = function (open_id) {
  var oauth = Cache.get(cache_keys.token);

  EventBus.$http.post(EventBus.$Config.baseUrl+ 'api/activity/bind/activity-wx', {
    open_id
  }, {
    headers: {
      Authorization: oauth.access_token
    }
  }).then(res => {
    res = res.data;

    if (res.status) {
      Cache.set(cache_keys.activity_openid, {
        openid: open_id,
        binded: true
      }, 0);
    } else {
      Cache.set(cache_keys.activity_openid, {
        openid: open_id
      }, 0);
    }
  }, () => {
    Cache.set(cache_keys.activity_openid, {
      openid: open_id
    }, 0);
  })
};


export const setUserCache = function () {

  var user_info = Cache.get(cache_keys.info);

  if (user_info) {

    Cache.set(cache_keys.info,user_info,'1m')

  }

  let oauth = Cache.get(cache_keys.token);



  if(oauth) {


    EventBus.$http.get(EventBus.$Config.baseUrl + 'api/me',
      {
        headers:{
          Authorization:oauth.access_token
        },params: {
        include: 'group,size'
      }}).then(resolve=>{
      // resolve = resolve.json()
      let res= resolve.data.data;

      if (!user_info || res.updated_at !== user_info.updated_at) {
        console.log(res)
        Cache.set(cache_keys.info,res,'1m')

      }

    })

  }


}
